package
        com.zzc.sale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hos.entity.stock.InventoryLog;
import com.hos.entity.stock.Medicines;
import com.hos.entity.stock.Purchase;
import com.hos.entity.stock.PurchaseItem;
import com.hos.utils.IdGeneratorUtil;
import com.hos.utils.WebUtil;
import com.hos.vo.Result;
import com.zzc.sale.feigns.UserFeign;
import com.zzc.sale.mapper.InventoryLogMapper;
import com.zzc.sale.mapper.MedicinesMapper;
import com.zzc.sale.mapper.PurchaseItemMapper;
import com.zzc.sale.mapper.PurchaseMapper;
import com.zzc.sale.service.PurchaseService;
import com.zzc.sale.vo.PurchaseVo;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author：xIAO_ZHOU_TX
 * @date：Created in 2023/12/18 16:21
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class PurchaseServiceImpl implements PurchaseService {
    @Resource
    private PurchaseMapper purchaseMapper;
    @Resource
    private PurchaseItemMapper purchaseItemMapper;
    @Resource
    private MedicinesMapper medicinesMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource
    private UserFeign userFeign;
    @Resource
    private InventoryLogMapper inventoryLogMapper;


    @Override
    public Page<Purchase> listPurchaseForPage(PurchaseVo purchaseVo) {
        Page<Purchase> page = new Page<>(purchaseVo.getPageNum(), purchaseVo.getPageSize());
        LambdaQueryWrapper<Purchase> wrapper = new LambdaQueryWrapper<>();
        // 供应商id
        if (StringUtils.hasText(purchaseVo.getProviderId())) {
            wrapper.eq(Purchase::getProviderId, purchaseVo.getProviderId());
        }
        // 申请人
        if (StringUtils.hasText(purchaseVo.getApplyUserName())) {
            wrapper.like(Purchase::getApplyUserName, purchaseVo.getApplyUserName());
        }
        // 单据状态
        if (StringUtils.hasText(purchaseVo.getStatus())) {
            wrapper.eq(Purchase::getStatus, purchaseVo.getStatus());
        }
        return purchaseMapper.selectPage(page, wrapper);
    }

    @Override
    public String generatePurchaseId() {
        return IdGeneratorUtil.nextId("CF");
    }

    @Override
    public Integer addPurchase(Purchase purchase) {
        return purchaseMapper.insert(purchase);
    }

    @Override
    public Result doInventory(String purchaseId) {
        String statusById = getStatusById(purchaseId);
        if (statusById.equals("3")) {
            LambdaQueryWrapper<PurchaseItem> wrapper = new LambdaQueryWrapper<>();
            //修改库存
            if (StringUtils.hasText(purchaseId)) {
                wrapper.eq(PurchaseItem::getPurchaseId, purchaseId);
                List<PurchaseItem> purchaseItems = purchaseItemMapper.selectList(wrapper);
                if(purchaseItems !=null){
                    for (PurchaseItem item : purchaseItems) {
                        //查询药品id==>得到药品库存
                        String id = item.getMedicinesId();
                        Medicines medicines = medicinesMapper.selectById(id);
                        Integer medicinesStockNum = medicines.getMedicinesStockNum();
                        Integer purchaseNumber = item.getPurchaseNumber();
                        Integer num =  purchaseNumber + medicinesStockNum;
                        //修改库存
                        LambdaUpdateWrapper<Medicines> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.eq(Medicines::getMedicinesId, item.getMedicinesId())
                                .set(Medicines::getMedicinesStockNum, num);
                        medicinesMapper.update(updateWrapper);
                        //添加批次库存

                        InventoryLog inventoryLog =new InventoryLog();
                        //单据号
                        inventoryLog.setPurchaseId(item.getPurchaseId());
                        //入库号
                        inventoryLog.setInventoryLogId(item.getItemId());
                        //药品名称
                        inventoryLog.setMedicinesName(item.getMedicinesName());
                        //生产厂家
                        inventoryLog.setProducterId(item.getProducterId());
                        //创建时间
                        inventoryLog.setCreateTime(new Date());
                        //药品id
                        inventoryLog.setMedicinesId(item.getMedicinesId());
                        Medicines medicines1 = medicinesMapper.selectById(inventoryLog.getMedicinesId());//获取药品信息
                        //处方价
                        inventoryLog.setPrescriptionPrice(medicines1.getPrescriptionPrice());
                        //处方类型
                        inventoryLog.setPrescriptionType(medicines1.getPrescriptionType());
                        //药品类型
                        inventoryLog.setMedicinesType(medicines1.getMedicinesType());
                        //采购数量
                        inventoryLog.setInventoryLogNum(item.getPurchaseNumber());
                        //处方额
                        Integer number = item.getPurchaseNumber();
                        BigDecimal big2 = new BigDecimal(number.toString());
                        BigDecimal price = medicines1.getPrescriptionPrice();
                        BigDecimal PrescriptionTotalAmount =big2.multiply(price);
                        inventoryLog.setPrescriptionTotalAmount(PrescriptionTotalAmount);
                        //批发价
                        inventoryLog.setTradePrice(item.getTradePrice());
                        //批发额
                        inventoryLog.setTradeTotalAmount(item.getTradeTotalAmount());
                        //批次号
                        inventoryLog.setBatchNumber(item.getBatchNumber());
                        //单位
                        inventoryLog.setUnit(item.getUnit());

                        inventoryLogMapper.insert(inventoryLog);
                    }
                }
            }


            // 获入库者信息
            String token = WebUtil.getToken();
            String userName = userFeign.selectUserByPhone(redisTemplate.opsForValue().get("user:" + token)).getUserName();
            LambdaUpdateWrapper<Purchase> purchaseLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            if (StringUtils.hasText(purchaseId)) {
                purchaseLambdaUpdateWrapper.eq(Purchase::getPurchaseId, purchaseId)
                        // 入库时间
                        .set(Purchase::getStorageOptTime, new Date())
                        // 入库人
                        .set(Purchase::getStorageOptUser, userName)
                        // 修改状态==>入库成功
                        .set(Purchase::getStatus, "6");
            }
            return new Result<>(200, "入库成功", purchaseMapper.update(purchaseLambdaUpdateWrapper));
        } else {
            return new Result<>(500, "审核通过后才可入库", null);
        }


    }

    @Override
    public String getStatusById(String purchaseId) {
        LambdaQueryWrapper<Purchase> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Purchase::getPurchaseId, purchaseId);
        Purchase purchase = purchaseMapper.selectOne(wrapper);
        return purchase.getStatus();
    }


    @Override
    public Page<Purchase> listPurchasePendingForPage(PurchaseVo purchaseVo) {
        Page<Purchase> page = new Page<>(purchaseVo.getPageNum(), purchaseVo.getPageSize());
        LambdaQueryWrapper<Purchase> wrapper = new LambdaQueryWrapper<>();
        purchaseVo.setStatus("2");
        // 供应商id
        if (StringUtils.hasText(purchaseVo.getProviderId())) {
            wrapper.eq(Purchase::getProviderId, purchaseVo.getProviderId());
        }
        // 申请人
        if (StringUtils.hasText(purchaseVo.getApplyUserName())) {
            wrapper.like(Purchase::getApplyUserName, purchaseVo.getApplyUserName());
        }
        // 单据状态
        if (StringUtils.hasText(purchaseVo.getStatus())) {
            wrapper.eq(Purchase::getStatus, purchaseVo.getStatus());
        }
        return purchaseMapper.selectPage(page, wrapper);


    }

    @Override
    public Integer auditPass(String purchaseId) {
        LambdaUpdateWrapper<Purchase> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Purchase::getPurchaseId, purchaseId)
                .set(Purchase::getStatus, "3")
                .set(Purchase::getAuditMsg,"已通过");
        return purchaseMapper.update(updateWrapper);
    }

    @Override
    public Integer auditNoPass(String purchaseId, String auditMsg) {
        LambdaUpdateWrapper<Purchase> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Purchase::getPurchaseId, purchaseId)
                .set(Purchase::getStatus, "4")
                .set(Purchase::getAuditMsg, auditMsg);
        return purchaseMapper.update(updateWrapper);
    }

    @Override
    public Result doAudit(String purchaseId) {
        String statusById = getStatusById(purchaseId);
        if (statusById.equals("1") || statusById.equals("4")) {
            LambdaUpdateWrapper<Purchase> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Purchase::getPurchaseId, purchaseId)
                    .set(Purchase::getStatus, "2");
            return new Result<>(200, "修改成功", purchaseMapper.update(updateWrapper));
        } else {
            return new Result<>(500, "只有未提交以及审核失败才可提交", null);

        }

    }

    @Override
    public Result doInvalid(String purchaseId) {
        String statusById = getStatusById(purchaseId);
        if (statusById.equals("1") || statusById.equals("4")) {
            LambdaUpdateWrapper<Purchase> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Purchase::getPurchaseId, purchaseId)
                    .set(Purchase::getStatus, "5");
            return new Result<>(200, "修改成功", purchaseMapper.update(updateWrapper));
        } else {
            return new Result<>(500, "只有未提交以及审核失败才可作废", null);

        }


    }


}

